package pr.iceworld.fernando.oms.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Service;
import pr.iceworld.fernando.entity.User;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class ShiroService<T> {

    @Resource
    UserService userService;

    public User<Long> login(Long id, String username, String email, String password) {
        User user = userService.getUserByIdOrUsernameOrEmail(id, username, email);
        this.validateAccount(user, password);
        this.hidePassword(user);
        return user;
    }

    public void validateAccount(User user, String password) {
        if (Objects.isNull(user)) {
            throw new UnknownAccountException();
        }
        if (User.STATUS_LOCKED == user.getStatus()) {
            throw new LockedAccountException();
        }
        validatePassword(user, password);
    }

    public void validatePassword(User user, String password) {
        if (!password.equals(user.getPassword())) {
            throw new IncorrectCredentialsException();
        }
    }

    private void hidePassword(User user) {
        user.setPassword(StringUtils.EMPTY);
    }
}
